﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;

namespace BlogExtractor {
	enum Setting { UseProxy, BlogUrl, GoogleToken }

	class Profile {
		string _blogUrl;
		bool? _useProxy;
		string _googleToken;

		internal string BlogUrl {
			get {
				if (string.IsNullOrEmpty(_blogUrl)) { _blogUrl = Load(Setting.BlogUrl); }
				return _blogUrl;
			}
			set { Save(Setting.BlogUrl, value); }
		}

		internal bool UseProxy {
			get {
				if (!_useProxy.HasValue) {
					string content = Load(Setting.UseProxy);
					_useProxy = content != null && bool.Parse(content);
				}
				return _useProxy.Value;
			}
			set {
				Save(Setting.UseProxy, value.ToString());
			}
		}

		internal string GoogleToken {
			get {
				if (string.IsNullOrEmpty(_googleToken)) { _googleToken = Load(Setting.GoogleToken); }
				return _googleToken;
			}
			set { Save(Setting.GoogleToken, value); }
		}

		/// <summary>
		/// Load settings file from isolated storage
		/// </summary>
		static string Load(Setting s) {
			string fileName = s.ToString();
			using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null)) {
				if (isoStore.GetFileNames(fileName).Length > 0) {
					using (StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, isoStore))) {
						return reader.ReadToEnd();
					}
				}
			}
			return null;
		}

		/// <summary>
		/// Save a setting to isolated storage
		/// </summary>
		static bool Save(Setting s, string value) {
			string fileName = s.ToString();
			bool success = false;
			using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null)) {
				using (StreamWriter writer = new StreamWriter(new IsolatedStorageFileStream(fileName, FileMode.Create, isoStore))) {
					try {
						writer.Write(value);
						success = true;
					} catch { }
				}
			}
			return success;
		}
	}
}
